import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  Upload,
  Tree,
  TreeSelect,
  Modal,
} from "antd";
import {
  PlusOutlined,
  ExclamationCircleFilled,
  DeleteOutlined,
  SearchOutlined,
  UploadOutlined,
  EditOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  key_find_check_value,
  box_type_list,
} from "../../utils";

export default function K12WxOrganization(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  const { Option } = Select;
  const { confirm } = Modal;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [company_scope, setCompany_scope] = useState("now");
  const [com_ids_par, setCom_ids_par] = useState([]);
  const [data_list, setData_list] = useState([]);
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: company_scope == "now" ? local_company_object.id : "",
      company: company_scope == "now" ? local_company_object.company : "",
      com_ids_par: com_ids_par.value,
    };
    setSpinning(true);
    let res = await post_axios("k12_wx_organization", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setData_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: "机构名称",
      dataIndex: "organization_name",
      align: "center",
    },
    {
      title: "机构id",
      dataIndex: "organization_id",
      align: "center",
    },
    {
      title: "wx_appid",
      dataIndex: "wx_appid",
      align: "center",
    },
    {
      title: "组织",
      dataIndex: "com",
      align: "center",
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});
  const tableRowClick = (row) => {
    console.log(row);
    setClickRowKey(row.organization_id);
    setclickRow(row);
    get_class_data(row);
  };

  const search_data = () => {
    setPage(1);
    initData();
  };

  const initData = () => {
    setClickRowKey("");
    setclickRow([]);

    setClicked_class_id("");
    setClicked_class_obj({});
    setClass_data_list([]);
    getData();
  };

  const [class_data_list, setClass_data_list] = useState();
  const get_class_data = async (row) => {
    let upMsg = {
      organization_id: row ? row.organization_id : clickRowKey,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("k12_wx_organization", "m_query_class", upMsg);
    if (!res) return;
    setClass_data_list(res.data_rows.rows);
  };

  // 编辑机构
  const [edit_organization_show, setEdit_organization_show] = useState(false);
  const [edit_organization_title, setEdit_organization_title] = useState(
    t("common.add")
  );
  const [edit_type, setEdit_type] = useState("add");

  const [edit_organization_name, setEdit_organization_name] = useState("");
  const [edit_organization_id, setEdit_organization_id] = useState("");
  const [edit_organization_wx_appid, setEdit_organization_wx_appid] =
    useState("");
  const [edit_organization_com_id, setEdit_organization_com_id] = useState("");
  const edit_organization_dialog_show = (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEdit_organization_name("");
      setEdit_organization_id("");
      setEdit_organization_wx_appid("");
      setEdit_organization_com_id("");

      setEdit_organization_show(true);
    } else {
      setEdit_organization_show(true);
    }
  };
  const edit_organization_confirm = async () => {
    if (edit_organization_com_id.length === 0) {
      message.warning({
        content: "请选择组织",
      });
      return;
    }
    if (edit_organization_name === "") {
      message.warning({
        content: "请输入机构名称",
      });
      return;
    }
    if (edit_organization_id === "") {
      message.warning({
        content: "请输入机构id",
      });
      return;
    }
    if (edit_organization_wx_appid === "") {
      message.warning({
        content: "请输入appid",
      });
      return;
    }

    let upMsg = {
      com_id: edit_organization_com_id,
      organization_name: edit_organization_name,
      organization_id: edit_organization_id,
      wx_appid: edit_organization_wx_appid,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let action = "m_add";
    if (edit_type == "change") {
      action = "m_modify";
    }
    let res = await post_axios("k12_wx_organization", action, upMsg);
    if (!res) return;
    message.success({
      content: t("common.successfully"),
    });
    setEdit_organization_show(false);
    search_data();
  };

  // 删除机构
  const delete_organization = async () => {
    if (clickRowKey === "") {
      message.warning({
        content: "请选择一个机构",
      });
      return;
    }
    let { com_id, organization_name, organization_id, wx_appid } = clickRow;

    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          是否确认删除机构：<strong>{organization_name}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          com_id,
          organization_name,
          organization_id,
          wx_appid,
          company_id: local_company_object.id,
          company: local_company_object.company,
        };
        let res = await post_axios("k12_wx_organization", "m_del", upMsg);
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  // 年级列表点击
  const [clicked_class_id, setClicked_class_id] = useState("");
  const [clicked_class_obj, setClicked_class_obj] = useState({});
  const class_row_click = (row) => {
    setClicked_class_id(JSON.parse(JSON.stringify(row)).org_class_id);
    setClicked_class_obj(row);
  };

  // 编辑年级
  const [edit_class_show, setEdit_class_show] = useState(false);
  const [edit_class_title, setEdit_class_title] = useState(t("common.add"));
  const [edit_class_type, setEdit_class_type] = useState("add");
  const [edit_class_name, setEdit_class_name] = useState("");

  const edit_class_dialog_show = (value) => {
    if (clickRowKey == "") {
      message.warning({
        content: "请选择一个机构",
      });
      return;
    }
    setEdit_class_type(value);
    if (value === "add") {
      setEdit_class_title(t("common.add"));
      setEdit_class_name("");

      setEdit_class_show(true);
    } else {
      if (clicked_class_id == "") {
        message.warning({
          content: "请选择一个年级",
        });
        return;
      }

      setEdit_class_title(t("common.edit"));

      setEdit_class_name(clicked_class_obj.org_class);
      setEdit_class_show(true);
    }
  };
  const edit_class_confirm = async () => {
    if (edit_class_name === "") {
      message.warning({
        content: "请输入年级名称",
      });
      return;
    }
    let upMsg = {
      organization_id: clickRowKey,
      org_class: edit_class_name,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let action = "m_add_class";
    if (edit_class_type == "change") {
      action = "m_modify_class";
      upMsg["org_class_id"] = clicked_class_id;
    }
    let res = await post_axios("k12_wx_organization", action, upMsg);
    if (!res) return;
    message.success({
      content: edit_class_title + " " + t("common.successfully"),
    });
    setEdit_class_show(false);
    setClicked_class_id("");
    setClicked_class_obj({});
    setClass_data_list([]);
    get_class_data();
  };
  // 删除年级
  const delete_class = async () => {
    if (clicked_class_id === "") {
      message.warning({
        content: "请选择一个年级",
      });
      return;
    }
    let { org_class, org_class_id, organization_id } = clicked_class_obj;

    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          是否确认删除年级：<strong>{org_class}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          org_class,
          org_class_id,
          organization_id,
          company_id: local_company_object.id,
          company: local_company_object.company,
        };
        let res = await post_axios("k12_wx_organization", "m_del_class", upMsg);
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        get_class_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  // 绑定机器
  const [edit_avm_show, setEdit_avm_show] = useState(false);
  const edit_avm_dialog_show = async () => {
    if (clickRowKey === "") {
      message.warning({
        content: "请选择一个年级",
      });
      return;
    }
    await bind_avm_search();
    setEdit_avm_show(true);
  };
  const [bind_avm_list, setBind_avm_list] = useState([]);
  const bind_avm_search = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      organization_id: clickRowKey,
    };
    let res = await post_axios("k12_wx_organization", "m_query_avm", upMsg);
    if (!res) return;
    setBind_avm_list(res.data_rows.rows);
  };
  const [click_avm, setClick_avm] = useState("");
  const [click_avm_rows, setClick_avm_rows] = useState({});
  const avm_row_click = (row) => {
    setClick_avm(row.avm);
    setClick_avm_rows(row);
  };
  const [avm, setAvm] = useState("");
  const [avm_add_show, setAvm_add_show] = useState(false);
  const bind_avm_add = () => {
    setAvm("");
    setAvm_add_show(true);
  };
  const bind_avm_add_confirm = async () => {
    if (avm === "") {
      message.warning({
        content: "请输入机器编号",
      });
      return;
    }
    let upMsg = {
      avm: avm,
      organization_id: clickRowKey,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("k12_wx_organization", "m_add_avm", upMsg);
    if (!res) return;
    message.success({
      content: t("common.add_scuuess"),
    });
    bind_avm_search();
    setAvm_add_show(false);
  };

  const bind_avm_del = async () => {
    if (click_avm === "") {
      message.warning({
        content: "请选择一个机器",
      });
      return;
    }
    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          是否确认删除机器：<strong>{click_avm}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          avm: click_avm,
          organization_id: clickRowKey,
          company_id: local_company_object.id,
          company: local_company_object.company,
        };
        let res = await post_axios("k12_wx_organization", "m_del_avm", upMsg);
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        bind_avm_search();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const classColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: "年级名称",
      dataIndex: "org_class",
      align: "center",
    },
  ];

  const avmColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("assets.avm"),
      dataIndex: "avm",
      align: "center",
    },
    {
      title: t("operate.project"),
      dataIndex: "project",
      align: "center",
    },
    {
      title: t("operate.point"),
      dataIndex: "point",
      align: "center",
    },
  ];

  // 获取组织列表
  const [com_list, setCom_list] = useState([]);
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };
  function treeNodeItem(node) {
    const { TreeNode } = TreeSelect;
    if (node.children) {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        >
          {node.children.map((child) => {
            return treeNodeItem(child);
          })}
        </TreeNode>
      );
    } else {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        />
      );
    }
  }
  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight = document.getElementsByClassName(
        "k12_wx_organization"
      )[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
      get_com_data();
    });
  }, []);
  return (
    <>
      <div className="k12_wx_organization modules">
        <div className="screen_ipt">
          {user_grade < 10 ? (
            <div className="ipt_box">
              <div className="ipt_box_title">{t("system_manager.company")}</div>
              <Select
                size="small"
                placeholder=" "
                options={[
                  {
                    label: t("system_manager.current_selected"),
                    value: "now",
                    key: "now",
                  },
                  {
                    label: t("system_manager.all"),
                    value: "*",
                    key: "*",
                  },
                ]}
                value={company_scope}
                onChange={(value) => setCompany_scope(value)}
              />
            </div>
          ) : (
            ""
          )}
          {user_grade < 70 ? (
            <div className="ipt_box ipt_box_long">
              <div className="ipt_box_title">{t("market.organization")}</div>
              <TreeSelect
                value={com_ids_par}
                treeData={com_list}
                allowClear={true}
                size="small"
                multiple
                treeCheckStrictly={true}
                fieldNames={{
                  label: "com",
                  value: "com_id",
                  children: "children",
                }}
                placeholder=" "
                treeCheckable={true}
                onChange={(newValue) => setCom_ids_par(newValue)}
              />
            </div>
          ) : (
            ""
          )}
        </div>
        <div className="screen_btn">
          <div className="btn_box" style={{ width: "60vw" }}>
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_organization_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_organization}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询设备 */}
            {menu_action.indexOf("m_query_avm") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={edit_avm_dialog_show}
              >
                {text_check(user_power_lang["m_query_avm"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
          <div className="btn_box" style={{ width: "40vw" }}>
            {/* 添加 */}
            {menu_action.indexOf("m_add_class") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_class_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add_class"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify_class") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_class_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify_class"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del_class") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_class}
              >
                {text_check(user_power_lang["m_del_class"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "59.9vw",
            }}
          >
            <Table
              dataSource={data_list}
              size="small"
              bordered
              columns={columns}
              rowKey="organization_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.organization_id == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>

          <div
            className="noPage-table"
            style={{
              width: "39.9vw",
            }}
          >
            <Table
              dataSource={class_data_list}
              size="small"
              bordered
              columns={classColumns}
              rowKey="org_class_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => class_row_click(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.org_class_id == clicked_class_id) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={false}
            />
          </div>
        </div>
      </div>

      <Modal
        title={edit_organization_title}
        open={edit_organization_show}
        onOk={edit_organization_confirm}
        onCancel={() => setEdit_organization_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("market.organization")}</div>
          <TreeSelect
            value={edit_organization_com_id}
            placeholder=" "
            popupMatchSelectWidth={300}
            onSelect={(value, node, extra) => {
              return setEdit_organization_com_id(value);
            }}
          >
            {com_list.map((item) => {
              return treeNodeItem(item);
            })}
          </TreeSelect>
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">机构名称</div>
          <Input
            placeholder=" "
            value={edit_organization_name}
            onChange={(e) => setEdit_organization_name(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">机构id</div>
          <Input
            placeholder=" "
            value={edit_organization_id}
            onChange={(e) => setEdit_organization_id(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">appid</div>
          <Input
            placeholder=" "
            value={edit_organization_wx_appid}
            onChange={(e) => setEdit_organization_wx_appid(e.target.value)}
          />
        </div>
      </Modal>

      <Modal
        title={edit_class_title}
        open={edit_class_show}
        onOk={edit_class_confirm}
        onCancel={() => setEdit_class_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">年级名称</div>
          <Input
            placeholder=" "
            value={edit_class_name}
            defaultValue={edit_class_name}
            onChange={(e) => setEdit_class_name(e.target.value)}
          />
        </div>
      </Modal>

      <Modal
        title="设备详情"
        open={edit_avm_show}
        onCancel={() => setEdit_avm_show(false)}
        classNames={{ body: "edit_dialog_body", wrapper: "edit_900_style" }}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <div className="export_btn">
          <div className="btn_box">
            {/* 添加 */}
            <Button
              size="small"
              type="text"
              icon={<PlusOutlined style={{ color: "#1677FF" }} />}
              onClick={bind_avm_add}
            >
              {text_check(user_power_lang["m_add"])}
            </Button>
            {/* 添加 */}
            <Button
              size="small"
              type="text"
              icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
              onClick={bind_avm_del}
            >
              {text_check(user_power_lang["m_del"])}
            </Button>
            {/* 查询 */}
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={bind_avm_search}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          </div>
        </div>

        <div className="noPage-table" style={{ height: "300px" }}>
          <Table
            dataSource={bind_avm_list}
            size="small"
            bordered
            columns={avmColumns}
            rowKey="avm"
            virtual
            scroll={{
              y: 300,
            }}
            onRow={(record) => {
              return {
                onClick: () => avm_row_click(record), // 点击行
              };
            }}
            rowClassName={(record, index) => {
              if (record.avm == click_avm) {
                return "row_clicked_style";
              }
            }}
            rowHoverable={false}
            pagination={false}
          />
        </div>
      </Modal>
      <Modal
        title="绑定机器"
        open={avm_add_show}
        onOk={bind_avm_add_confirm}
        onCancel={() => setAvm_add_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">机器号</div>
          <Input
            placeholder=" "
            value={avm}
            defaultValue={avm}
            onChange={(e) => setAvm(e.target.value)}
          />
        </div>
      </Modal>
    </>
  );
}
